<?php

namespace App\Http\Controllers;

use App\Http\Requests\ExchangeController\StoreRequest;
use App\Http\Resources\ExchangeListResource;
use App\Models\Account;
use App\Models\Exchange;
use App\Models\Game;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Xrfg\Core\Trading\Account\Models\Account as TradingAccount;

class ExchangeController extends Controller
{
    /**
     * 兑换.
     */
    public function exchange(StoreRequest $request)
    {
        /** @var User $user */
        $user = Auth::user();
        $dse_number = $request->input('dse_number'); // DSE数量
        $dse_price = bcadd(Game::orderByDesc('id')->value('price'), 0, 2);
        if ($dse_price <= 0) {
            $this->error(30012);
        }
        $usdt_number = bcmul($dse_price, $dse_number);

        /** @var Account $outAccount */
        $outAccount = Account::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => 2,
        ])->refresh();
        /** @var TradingAccount $inAccount */
        $inAccount = TradingAccount::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => 1,
        ]);

        if ($outAccount->freeze < $dse_number) {
            $this->error(30008);
        }

        // 兑换记录
        $exchange = new Exchange();
        $exchange->user_id = $user->id;
        $exchange->usdt_number = $usdt_number;
        $exchange->rate = $dse_price;
        $exchange->bp_number = -$dse_number;
        $exchange->time = now();

        Log::info("兑换，user_id：{$user->id}，usdt_number：{$usdt_number}，dse_number：{$dse_number}");
        try {
            DB::transaction(function () use ($outAccount, $inAccount, $exchange, $usdt_number, $dse_number) {
                /** @var Account $outAccount */
                $outAccount = Account::lockForUpdate()->find($outAccount->id);
                /** @var TradingAccount $inAccount */
                $inAccount = TradingAccount::lockForUpdate()->find($inAccount->id);

                $exchange->save();

                $outAccount->freezeDecrement($dse_number);
                $outAccount->type = '兑换';
                $outAccount->action_id = $exchange->id;
                $outAccount->save();

                $inAccount->availableIncrement($usdt_number);
                $inAccount->proofId = [$exchange->id, 3, 7];
                $inAccount->save();

            });
        } catch (\Exception $exception) {
            Log::error($exception);
            $this->error();
        }

        Log::info("兑换成功");
        return $this->null();

    }

    /**
     * 兑换记录.
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;

        $list = Exchange::where('user_id', Auth::id())
            ->orderByDesc('id')
            ->paginate($perPage)
            ->appends($request->only(['per_page']));

        return ExchangeListResource::collection($list);
    }
}
